package cn.itsource.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.domain.Employee;
import cn.itsource.domain.Login;
import cn.itsource.domain.Tenant;
import cn.itsource.dto.LoginMealDto;
import cn.itsource.dto.RegisterFormDTO;
import cn.itsource.exception.MyException;
import cn.itsource.feign.client.LoginFeignClient;
import cn.itsource.mapper.EmployeeMapper;
import cn.itsource.mapper.TenantMapper;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengluochen
 * @since 2022-11-08
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private TenantMapper tenantMapper;
    @Autowired
    private LoginFeignClient loginFeignClient;
    @Override
    @GlobalTransactional
    public JSONResult register(RegisterFormDTO dto) {
        //准备储存员工表
        Employee employee = dto.getEmployee();
        employeeMapper.insert(employee);
        //准备储存adminId
        Tenant tenant = dto.getTenant();
        tenant.setAdminId(employee.getId());
        //准备储存租户表
        tenantMapper.insert(tenant);
        //准备储存login表
        Login login = new Login();
        login.setUsername(dto.getUsername());
        login.setPassword(SecureUtil.md5(dto.getPassword()));
        JSONResult result= loginFeignClient.save(login);
        //看是否成功
        if(!result.isSuccess()){
            throw  new MyException(result.getMessage());
        }
        Integer resultData = (Integer)result.getData();
        Long LoginId = Long.valueOf(resultData);
        //准备更新员工表
        employee.setTenantId(tenant.getId());
        employee.setLoginId(LoginId);
        employeeMapper.updateById(employee);
        //准备储存meal表
        LoginMealDto loginMealDto = new LoginMealDto();
        loginMealDto.setLoginId(LoginId);
        loginMealDto.setMealId(dto.getMealId());
        //设置7天后
        loginMealDto.setExpireDate(DateUtils.addDays(new Date(),7));

        JSONResult result1 = loginFeignClient.saveLoginMeal(loginMealDto);

        if(!result1.isSuccess()){
            throw  new MyException(result.getMessage());
        }
        System.out.println(1/0);
        return JSONResult.success();
    }
}
